<template>
  <div class="notice-container">
    <!-- 头部标题区域 -->
    <div class="page-header animate__animated animate__fadeInDown">
      <h2 class="page-title">公告管理</h2>
      <el-button type="primary" icon="el-icon-plus" @click="save">新增公告</el-button>
    </div>

    <!-- 搜索卡片区域 -->
    <el-card class="search-card animate__animated animate__fadeInDown">
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input placeholder="请输入公告标题" v-model="title" prefix-icon="el-icon-document"></el-input>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入创建者" v-model="user" prefix-icon="el-icon-user"></el-input>
          </el-col>
          <el-col :span="12" class="search-buttons">
            <el-button type="primary" icon="el-icon-search" @click="load">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteBatch" v-if="multipleSelection.length > 0">批量删除</el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card animate__animated animate__fadeInUp">
      <el-table 
        :data="tableData" 
        border 
        stripe 
        :header-cell-style="{background:'#f5f7fa', color:'#606266', fontWeight: 'bold'}"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="公告标题" min-width="120"></el-table-column>
        <el-table-column prop="content" label="公告内容" min-width="250">
          <template slot-scope="scope">
            <div class="content-preview">{{ scope.row.content }}</div>
            <el-button type="text" @click="viewContent(scope.row)" v-if="scope.row.content && scope.row.content.length > 50">查看全文</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="user" label="创建者" width="120"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-popconfirm
                  confirm-button-text='确定'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除此公告吗？"
                  @confirm="handleDelete(scope.row.id)"
                  @cancel="cancel">
                <el-button slot="reference" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-section">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑公告弹窗 -->
    <el-dialog :title="form.id ? '编辑公告' : '新增公告'" :visible.sync="dialogFormVisible" width="50%" @close="handleCancel">
      <el-form :model="form" :rules="rules" ref="noticeForm" label-position="right" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            :rows="10" 
            placeholder="请输入公告内容"
            resize="none">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看公告内容弹窗 -->
    <el-dialog title="公告详情" :visible.sync="viewDialogVisible" width="60%" center>
      <div class="notice-detail">
        <h3 class="notice-title">{{ currentNotice.title }}</h3>
        <div class="notice-meta">
          <span>创建者: {{ currentNotice.user }}</span>
          <span>创建时间: {{ currentNotice.createTime }}</span>
        </div>
        <div class="notice-content">{{ currentNotice.content }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DataSelect from "@/components/DataSelect";
import ImgUpload from "@/components/ImgUpload";
import 'animate.css/animate.min.css';

export default {
  name: "Notice",
  components: {ImgUpload, DataSelect},
  data() {
    return {
      pageSize: 10,
      pageNum: 1,
      title: '',
      user: '',
      tableData: [],
      dialogFormVisible: false,
      viewDialogVisible: false,
      currentNotice: {},
      form: {
        title: '',
        content: ''
      },
      formLabelWidth: '80px',
      multipleSelection: [],
      total: 0,
      rules: {
        title: [
          {required: true, message: '请输入公告标题', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入公告内容', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.request.get("/notice/findPage", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.title,
          user: this.user,
        }
      }).then(res => {
        if (res && res.data) {
          this.tableData = res.data.records || [];
          this.total = res.data.total || 0;
        } else {
          this.tableData = [];
          this.total = 0;
          console.error('Response data is null:', res);
        }
      }).catch(error => {
        console.error('Error loading notice data:', error);
        this.tableData = [];
        this.total = 0;
      });
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 0) {
        return 'even-row';
      } else {
        return 'odd-row';
      }
    },
    viewContent(row) {
      this.currentNotice = row;
      this.viewDialogVisible = true;
    },
    reset() {
      this.title = '';
      this.user = '';
      this.load();
    },
    save() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    handleCancel(){
      this.dialogFormVisible = false;
      Object.keys(this.form).forEach(key => {
        this.form[key] = '';
      });
    },
    handleAdd() {
      this.$refs.noticeForm.validate((valid) => {
        if (valid) {
          this.request.post("/notice/save", this.form).then(res => {
            if (res.code === '200') {
              if (this.form.id) {
                this.$message.success('编辑成功');
              } else {
                this.$message.success('新增成功');
              }
              this.dialogFormVisible = false;
              this.load();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogFormVisible = true;
    },
    handleDelete(id) {
      if (id) {
        this.request.delete('/notice/deleteById/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success('删除数据成功');
            this.handleCalPageNum();
          } else {
            this.$message.error(res.msg)
          }
        })
      } else {
        this.$message.error('没有id信息，无法删除');
      }
    },
    cancel() {
      this.$message({
        type: 'info',
        message: '已取消操作'
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请先选择要删除的数据");
        return
      }
      this.$confirm('确定要批量删除选中的公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.multipleSelection.map(v => v.id);
        this.request.post('/notice/deleteBatch', ids).then(res => {
          if (res.code === '200') {
            this.$message.success('批量删除成功');
            this.handleCalPageNum();
          } else {
            this.$message.error(res.msg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.load();
    },
    handleCalPageNum() {
      this.request.get("/notice/findPage", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.total = res.data.total;
        this.pageNum = (this.total % this.pageSize === 0) ? (this.total / this.pageSize) : Math.floor((this.total / this.pageSize) + 1);
        if (this.pageNum < 1) {
          this.pageNum = 1;
        }
        this.load();
      })
    }
  }
}
</script>

<style scoped>
.notice-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-section {
  width: 100%;
}

.search-buttons {
  display: flex;
  justify-content: flex-start;
}

.table-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.content-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 250px;
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-button {
  margin-right: 5px;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  border-top: 1px solid #e4e7ed;
  padding: 15px 20px;
}

.even-row {
  background-color: #fafafa;
}

.odd-row {
  background-color: #ffffff;
}

.notice-detail {
  padding: 10px;
}

.notice-title {
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 15px;
  color: #303133;
}

.notice-meta {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.notice-content {
  padding: 15px;
  min-height: 200px;
  background-color: #f5f7fa;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.6;
}
</style>
